import { Button, Card, Form, Input, message, Modal } from 'antd';
import React, { useState, useEffect } from 'react';

import {
  valueApproveSaveSupervisePUT,
  valueApproveCancelSupervisePUT,
} from '@/services/ValueApprovelMgr';
import * as api from '@/services/GatewayNewsMgr';
import _ from 'lodash';
import moment from 'moment';
import LayoutPage, { ProTitle } from './components/LayoutPage';
import { getCoreWarnInfoList } from '../ValueManage/PriceManage/Approve/utils/treeUtils';
import WarningBriefing from '../ValueManage/PriceManage/Approve/components/WarningBriefing';
import IndicatorImpact from '../ValueManage/PriceManage/Approve/components/IndicatorImpact';
import PriceAdjustmentBuilding from '../ValueManage/PriceManage/Approve/components/PriceAdjustmentBuilding';
import { FormProfessionalAdvice, FormSuperviseInfo } from './components/ProForm';

function closeBrowser() {
  if (navigator.userAgent.indexOf('MSIE') > 0) {
    // close IE
    if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
      window.opener = null;
      window.close();
    } else {
      window.open('', '_top');
      window.top.close();
    }
  } else {
    // close chrome;It is effective when it is only one.
    window.location.href = '';
    window.open('', '_self');
    window.close();
  }
}

function isEmpty(obj) {
  const reg = '^[ ]+$';
  const re = new RegExp(reg);
  if (typeof obj === 'undefined' || obj == null || obj === '' || re.test(obj)) {
    return true;
  }
  return false;
}

// 货值督办预警待办信息
function WarningSupervise(props) {
  const { validateFields } = props.form;
  const { instanceId, userId } = props.location.query;
  const [btnLoading1, setBtnLoading1] = useState(false);
  const [btnLoading2, setBtnLoading2] = useState(false);
  const [btnLoading3, setBtnLoading3] = useState(false);
  const [pageLoading, setPageLoading] = useState(false);
  const [dataState, setDataState] = useState({});
  const [visibleModal, setVisibleModal] = useState(false);
  const [cancelDesc, setCancelDesc] = useState('');

  const requestData = async () => {
    setPageLoading(true);
    const res = await api.commonGetWarnSupervisePcToDoGET({ params: { instanceId, userId } });
    if (res?.code === 1) {
      const arr = _.cloneDeep(res.data.bulletinWarnInfo);
      // 拼接完成标准描述信息
      let str = `督办内容：${res.data?.projectName || '-'};<br>`;
      if (arr?.length > 0) {
        arr.forEach(item => {
          if (item.status === 'warning') {
            str += `${item.content}<br>`;
          }
        });
        // 去掉多余的br
        str = str.replace(/<br><br>/g, '');
        res.data.warnConfirmInfo.completionCriteriaDesc = str;
        // 如果督办完成要求为空 赋默认值
        if (isEmpty(res.data.warnConfirmInfo.finishAsk)) {
          res.data.warnConfirmInfo.finishAsk = '请对本条审批作补充解释';
        }
        // 本次调价楼栋
        const bulidWarnInfoList = {
          marsVersions: res?.data.bulidWarnInfoList?.map(item => item.marsVersion),
          list: res?.data.bulidWarnInfoList,
        };
        // 核心指标
        const coreWarnInfoList = {
          marsVersions: res?.data.coreWarnInfoList?.map(item => item.marsVersion),
          list: getCoreWarnInfoList(res?.data.coreWarnInfoList),
        };
        setDataState({ ...res?.data, coreWarnInfoList, bulidWarnInfoList });
      }
    }
    setPageLoading(false);
  };

  // 消除待办
  const setEliminateToDo = () => {
    api
      .cleanPcToDoUsingGET({
        params: {
          instanceId,
          operatorType: '4', // 操作类型 (3-删除代办 4-待办转已办 )
          projectId: '',
          todoTypeCode: '',
        },
      })
      .then(res => {
        if (res?.code === 1) message.success(res.message, 1, () => closeBrowser());
      });
  };
  // 发起督办
  const handlerSubmitInitSupervision = () => {
    setBtnLoading1(true);
    validateFields(async (err, values) => {
      if (!err) {
        if (isEmpty(dataState?.marketingOpinionDesc) && isEmpty(dataState?.marketingSuggest)) {
          message.warning('营销人员未反馈意见');
        } else if (isEmpty(values.finishAsk)) {
          message.warning('督办完成要求未填写');
        } else {
          const result = await api.commonSendWarnSuperviseGET({ params: { instanceId } });
          if (result?.code === 1) setEliminateToDo();
        }
      }
    });
    setBtnLoading1(false);
  };

  // 点击保存意见
  const handlerSubmitOpinions = () => {
    setBtnLoading2(true);
    validateFields(async (err, values) => {
      if (!err) {
        const finishTime = values?.finishTime || dataState.warnConfirmInfo?.finishTime;
        const data = {
          taskId: instanceId,
          position: dataState.position, // 岗位
          ...values,
        };
        if (dataState.position === 'operation') {
          data.finishTime = moment(finishTime).format('YYYY-MM-DD HH:mm:ss'); // 督办完成时间
          data.feedbackLoopCount = dataState?.warnConfirmInfo?.feedbackLoopCount || 3; // 反馈周期天数
        }
        const result = await valueApproveSaveSupervisePUT({ data });
        if (result.code === 1) {
          message.success(result.message, 1, () => requestData());
        }
      }
    });
    setBtnLoading2(false);
  };

  // 无需质询发送按钮
  const handlerSubmitNotDoubt = async () => {
    setBtnLoading3(true);
    if (!isEmpty(cancelDesc)) {
      const result = await valueApproveCancelSupervisePUT({
        data: { cancelDesc, taskId: instanceId },
      });
      if (result?.code === 1) setEliminateToDo();
      setBtnLoading3(false);
    } else {
      message.warning('请填写说明');
      setBtnLoading3(false);
    }
  };

  // 点击无需质询按钮
  const handlerISNotDoubt = () => {
    const fieldNames = ['marketingOpinionDesc', 'marketingSuggest'];
    validateFields(fieldNames, err => {
      if (!err) setVisibleModal(true);
    });
  };

  // 初始化
  useEffect(() => {
    requestData();
  }, []);

  const FooterNode = () => {
    if (!_.isEmpty(dataState) && dataState.position) {
      return (
        <>
          {dataState?.position === 'operation' && (
            <Button
              type="primary"
              loading={btnLoading1}
              onClick={handlerSubmitInitSupervision}
              disabled={pageLoading || dataState?.todoStatus !== '0'}
            >
              发起督办
            </Button>
          )}
          <Button
            style={{ margin: '0 5px' }}
            type="primary"
            loading={btnLoading2}
            onClick={handlerSubmitOpinions}
            disabled={pageLoading || dataState?.todoStatus !== '0'}
          >
            保存意见
          </Button>
          {dataState?.position === 'operation' && (
            <Button
              type="danger"
              loading={btnLoading3}
              onClick={handlerISNotDoubt}
              disabled={pageLoading || dataState?.todoStatus !== '0'}
            >
              无需质询
            </Button>
          )}
        </>
      );
    }
    return <></>;
  };

  return (
    <LayoutPage header={dataState?.name || ''} footer={<FooterNode />}>
      <Card>
        <ProTitle>预警信息</ProTitle>
        <WarningBriefing
          warnFlag
          data={dataState?.bulletinWarnInfo || []}
          loading={pageLoading}
          contrastType={dataState?.contrastType}
        />
        <br />
        <IndicatorImpact
          data={dataState?.coreWarnInfoList || []}
          loading={pageLoading}
          contrastType={dataState?.contrastType}
        />
        <br />
        <PriceAdjustmentBuilding
          data={dataState?.bulidWarnInfoList || []}
          loading={pageLoading}
          contrastType={dataState?.contrastType}
        />
      </Card>

      {/* form 表单 */}
      <Form layout="inline">
        {dataState?.position && (
          <>
            <br />
            <Card>
              <ProTitle>专业意见</ProTitle>
              <FormProfessionalAdvice {...props} data={dataState} />
            </Card>
          </>
        )}
        {/* 运营才显示督办信息 */}
        {dataState?.position === 'operation' && (
          <>
            <br />
            <Card>
              <ProTitle>督办信息</ProTitle>
              <FormSuperviseInfo {...props} data={dataState} />
            </Card>
          </>
        )}
      </Form>

      <Modal
        title="无需质询将会消除待办"
        visible={visibleModal}
        onCancel={() => setVisibleModal(false)}
        onOk={handlerSubmitNotDoubt}
        confirmLoading={btnLoading3}
      >
        <Input.TextArea
          rows={5}
          placeholder="请输入无需质询说明"
          onChange={ev => setCancelDesc(ev.target.value)}
        />
      </Modal>
    </LayoutPage>
  );
}
const WarningSuperviseJsx = Form.create()(WarningSupervise);
export default WarningSuperviseJsx;
